<template>
    <div class="course-management">
        <div class="page-header">
            <h1>课程管理</h1>
            <a-button type="primary" @click="showAddModal = true">
                <template #icon>
                    <PlusOutlined />
                </template>
                添加课程
            </a-button>
        </div>

        <!-- 搜索和筛选 -->
        <div class="search-section">
            <a-row :gutter="16">
                <a-col :span="6">
                    <a-input-search v-model:value="searchKeyword" placeholder="搜索课程名称" @search="handleSearch" />
                </a-col>
                <a-col :span="4">
                    <a-select v-model:value="selectedCategory" placeholder="选择分类" style="width: 100%"
                        @change="handleCategoryChange">
                        <a-select-option value="">全部分类</a-select-option>
                        <a-select-option value="frontend">前端开发</a-select-option>
                        <a-select-option value="backend">后端开发</a-select-option>
                        <a-select-option value="ai">AI人工智能</a-select-option>
                        <a-select-option value="cloud">云计算</a-select-option>
                    </a-select>
                </a-col>
                <a-col :span="4">
                    <a-select v-model:value="selectedStatus" placeholder="选择状态" style="width: 100%"
                        @change="handleStatusChange">
                        <a-select-option value="">全部状态</a-select-option>
                        <a-select-option value="published">已发布</a-select-option>
                        <a-select-option value="draft">草稿</a-select-option>
                        <a-select-option value="archived">已归档</a-select-option>
                    </a-select>
                </a-col>
                <a-col :span="4">
                    <a-button @click="resetFilters">重置筛选</a-button>
                </a-col>
            </a-row>
        </div>

        <!-- 课程列表 -->
        <div class="course-table">
            <a-table :columns="columns" :data-source="filteredCourses" :pagination="pagination" :loading="loading"
                row-key="id">
                <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'cover'">
                        <img :src="record.cover" :alt="record.title" class="course-cover" />
                    </template>
                    <template v-else-if="column.key === 'price'">
                        <span class="price">¥{{ record.price }}</span>
                    </template>
                    <template v-else-if="column.key === 'status'">
                        <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
                    </template>
                    <template v-else-if="column.key === 'difficulty'">
                        <a-tag :color="getDifficultyColor(record.difficulty)">{{ record.difficulty }}</a-tag>
                    </template>
                    <template v-else-if="column.key === 'action'">
                        <a-space>
                            <a-button type="link" @click="editCourse(record)">编辑</a-button>
                            <a-button type="link" @click="viewCourse(record)">查看</a-button>
                            <a-popconfirm title="确定要删除这个课程吗？" @confirm="deleteCourse(record.id)">
                                <a-button type="link" danger>删除</a-button>
                            </a-popconfirm>
                        </a-space>
                    </template>
                </template>
            </a-table>
        </div>

        <!-- 添加/编辑课程弹窗 -->
        <a-modal v-model:open="showAddModal" :title="isEditing ? '编辑课程' : '添加课程'" width="800px" @ok="handleSubmit"
            @cancel="handleCancel">
            <a-form ref="formRef" :model="courseForm" :rules="formRules" layout="vertical">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="课程名称" name="title">
                            <a-input v-model:value="courseForm.title" placeholder="请输入课程名称" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="课程分类" name="category">
                            <a-select v-model:value="courseForm.category" placeholder="选择分类">
                                <a-select-option value="frontend">前端开发</a-select-option>
                                <a-select-option value="backend">后端开发</a-select-option>
                                <a-select-option value="ai">AI人工智能</a-select-option>
                                <a-select-option value="cloud">云计算</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="课程价格" name="price">
                            <a-input-number v-model:value="courseForm.price" :min="0" :precision="2" style="width: 100%"
                                placeholder="请输入价格" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="课程难度" name="difficulty">
                            <a-select v-model:value="courseForm.difficulty" placeholder="选择难度">
                                <a-select-option value="初级">初级</a-select-option>
                                <a-select-option value="中级">中级</a-select-option>
                                <a-select-option value="高级">高级</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-form-item label="课程封面" name="cover">
                    <a-upload v-model:file-list="fileList" list-type="picture-card" :show-upload-list="false"
                        :before-upload="beforeUpload">
                        <img v-if="courseForm.cover" :src="courseForm.cover" alt="cover" />
                        <div v-else>
                            <PlusOutlined />
                            <div style="margin-top: 8px">上传封面</div>
                        </div>
                    </a-upload>
                </a-form-item>

                <a-form-item label="课程描述" name="description">
                    <a-textarea v-model:value="courseForm.description" :rows="4" placeholder="请输入课程描述" />
                </a-form-item>

                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="课程时长" name="duration">
                            <a-input v-model:value="courseForm.duration" placeholder="如：20小时" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="课程状态" name="status">
                            <a-select v-model:value="courseForm.status" placeholder="选择状态">
                                <a-select-option value="draft">草稿</a-select-option>
                                <a-select-option value="published">已发布</a-select-option>
                                <a-select-option value="archived">已归档</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-form-item label="课程亮点" name="highlights">
                    <a-textarea v-model:value="courseForm.highlights" :rows="3" placeholder="请输入课程亮点，每行一个" />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import type { FormInstance } from 'ant-design-vue'

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const selectedCategory = ref('')
const selectedStatus = ref('')
const showAddModal = ref(false)
const isEditing = ref(false)
const fileList = ref([])
const formRef = ref<FormInstance>()

// 课程表单
const courseForm = reactive({
    id: null,
    title: '',
    category: '',
    price: 0,
    difficulty: '',
    cover: '',
    description: '',
    duration: '',
    status: 'draft',
    highlights: ''
})

// 表单验证规则
const formRules = {
    title: [{ required: true, message: '请输入课程名称' }],
    category: [{ required: true, message: '请选择课程分类' }],
    price: [{ required: true, message: '请输入课程价格' }],
    difficulty: [{ required: true, message: '请选择课程难度' }],
    description: [{ required: true, message: '请输入课程描述' }]
}

// 分页配置
const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条记录`
})

// 表格列配置
const columns = [
    {
        title: '封面',
        dataIndex: 'cover',
        key: 'cover',
        width: 80
    },
    {
        title: '课程名称',
        dataIndex: 'title',
        key: 'title',
        width: 200
    },
    {
        title: '分类',
        dataIndex: 'category',
        key: 'category',
        width: 100
    },
    {
        title: '价格',
        dataIndex: 'price',
        key: 'price',
        width: 100
    },
    {
        title: '难度',
        dataIndex: 'difficulty',
        key: 'difficulty',
        width: 80
    },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 100
    },
    {
        title: '学习人数',
        dataIndex: 'students',
        key: 'students',
        width: 100
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 150
    },
    {
        title: '操作',
        key: 'action',
        width: 200,
        fixed: 'right'
    }
]

// 课程数据
const courses = reactive([
    {
        id: 1,
        title: 'AI智能体开发实战',
        category: 'ai',
        price: 999,
        difficulty: '高级',
        cover: 'https://via.placeholder.com/80x60/1890ff/ffffff?text=AI',
        status: 'published',
        students: 1234,
        createTime: '2024-01-15',
        description: '从零开始学习AI智能体开发',
        duration: '20小时',
        highlights: '从零开始，循序渐进\n实战项目驱动学习\nAI最新技术栈'
    },
    {
        id: 2,
        title: 'Vue3实战开发',
        category: 'frontend',
        price: 399,
        difficulty: '中级',
        cover: 'https://via.placeholder.com/80x60/13c2c2/ffffff?text=Vue3',
        status: 'published',
        students: 5678,
        createTime: '2024-01-10',
        description: '基于Vue3的现代前端开发',
        duration: '15小时',
        highlights: 'Vue3最新特性\nTypeScript支持\n实战项目'
    },
    {
        id: 3,
        title: 'SpringBoot微服务',
        category: 'backend',
        price: 599,
        difficulty: '高级',
        cover: 'https://via.placeholder.com/80x60/52c41a/ffffff?text=Spring',
        status: 'draft',
        students: 2345,
        createTime: '2024-01-08',
        description: '企业级微服务架构开发',
        duration: '25小时',
        highlights: '微服务架构\nSpring Cloud\nDocker部署'
    }
])

// 计算属性
const filteredCourses = computed(() => {
    return courses.filter(course => {
        const keywordMatch = !searchKeyword.value ||
            course.title.toLowerCase().includes(searchKeyword.value.toLowerCase())
        const categoryMatch = !selectedCategory.value || course.category === selectedCategory.value
        const statusMatch = !selectedStatus.value || course.status === selectedStatus.value

        return keywordMatch && categoryMatch && statusMatch
    })
})

// 方法
const handleSearch = () => {
    console.log('搜索:', searchKeyword.value)
}

const handleCategoryChange = () => {
    console.log('分类筛选:', selectedCategory.value)
}

const handleStatusChange = () => {
    console.log('状态筛选:', selectedStatus.value)
}

const resetFilters = () => {
    searchKeyword.value = ''
    selectedCategory.value = ''
    selectedStatus.value = ''
}

const editCourse = (course: any) => {
    isEditing.value = true
    Object.assign(courseForm, course)
    showAddModal.value = true
}

const viewCourse = (course: any) => {
    console.log('查看课程:', course.title)
}

const deleteCourse = (id: number) => {
    const index = courses.findIndex(course => course.id === id)
    if (index > -1) {
        courses.splice(index, 1)
    }
    console.log('删除课程:', id)
}

const beforeUpload = (file: File) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
        console.error('只能上传 JPG/PNG 格式的图片!')
        return false
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
        console.error('图片大小不能超过 2MB!')
        return false
    }

    // 模拟上传
    const reader = new FileReader()
    reader.onload = (e) => {
        courseForm.cover = e.target?.result as string
    }
    reader.readAsDataURL(file)

    return false
}

const handleSubmit = async () => {
    try {
        await formRef.value?.validate()

        if (isEditing.value) {
            // 编辑课程
            const index = courses.findIndex(course => course.id === courseForm.id)
            if (index > -1) {
                Object.assign(courses[index], courseForm)
            }
        } else {
            // 添加课程
            const newCourse = {
                ...courseForm,
                id: Date.now(),
                students: 0,
                createTime: new Date().toISOString().split('T')[0]
            }
            courses.unshift(newCourse)
        }

        showAddModal.value = false
        resetForm()
    } catch (error) {
        console.error('表单验证失败:', error)
    }
}

const handleCancel = () => {
    showAddModal.value = false
    resetForm()
}

const resetForm = () => {
    Object.assign(courseForm, {
        id: null,
        title: '',
        category: '',
        price: 0,
        difficulty: '',
        cover: '',
        description: '',
        duration: '',
        status: 'draft',
        highlights: ''
    })
    isEditing.value = false
    fileList.value = []
}

const getStatusColor = (status: string) => {
    const colors = {
        'published': 'green',
        'draft': 'orange',
        'archived': 'red'
    }
    return colors[status as keyof typeof colors] || 'blue'
}

const getStatusText = (status: string) => {
    const texts = {
        'published': '已发布',
        'draft': '草稿',
        'archived': '已归档'
    }
    return texts[status as keyof typeof texts] || status
}

const getDifficultyColor = (difficulty: string) => {
    const colors = {
        '初级': 'green',
        '中级': 'orange',
        '高级': 'red'
    }
    return colors[difficulty as keyof typeof colors] || 'blue'
}
</script>

<style scoped>
.course-management {
    padding: 0;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}

.page-header h1 {
    margin: 0;
    color: #333;
}

.search-section {
    background: #f5f5f5;
    padding: 16px;
    border-radius: 8px;
    margin-bottom: 16px;
}

.course-table {
    background: #fff;
    border-radius: 8px;
}

.course-cover {
    width: 60px;
    height: 45px;
    object-fit: cover;
    border-radius: 4px;
}

.price {
    color: #f5222d;
    font-weight: bold;
}

.ant-upload-select-picture-card {
    width: 120px;
    height: 90px;
}

.ant-upload-select-picture-card img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
</style>